package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.List;

import common.InvocationTypeEnum;

public class UDPServer {
	List<BankAccount> data;

	public static void main(String args[]) throws SocketException {
		// SocketManager socketManager;
		RequestHandler requestManager = new RequestHandler();
		int choice = 0;
		InvocationTypeEnum invo = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Please choose invocation semantics:");
		System.out.println("1. At-Least-Once");
		System.out.println("2. At-Most-Once");
		try {
			choice = Integer.parseInt(br.readLine());
		} catch (NumberFormatException | IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		switch (choice){
		case 1:
			invo = InvocationTypeEnum.AT_LEAST_ONCE;
			break;
		case 2:
			invo = InvocationTypeEnum.AT_MOST_ONCE;
			break;
		}
		System.out.println(invo.getMsg());
		try {
			while (true) {
				DatagramPacket requestPacket = SocketManager.getCurrent()
						.GetPacket();
				// Create reply Datagram Packet
				DatagramPacket replyPacket = requestManager
						.HandleRequest(requestPacket,invo);
				double a = Math.random();
				if (a < 0.5) {
					SocketManager.getCurrent().SendPacket(replyPacket);
				} else
					System.out.println("a = " + a
							+ ", Simulate lost request package");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SocketManager.getCurrent().CloseSocket();
			requestManager.cancelTimer();
		}
	}
}
